package com.xiaouyudeguang.common.config;

import com.xiaouyudeguang.common.annotation.ApiResource;
import com.xiaouyudeguang.common.collect.MapBuilder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Data
@Slf4j
@Configuration
@EnableOpenApi
@ConfigurationProperties("api.doc")
public class Knife4jConfiguration implements BeanFactoryAware, InitializingBean {

    private DefaultListableBeanFactory listableBeanFactory;

    @Value("${knife4j.enable:false}")
    private Boolean enabled;

    private Map<String, String> tags;

    @Override
    public void setBeanFactory(@NotNull BeanFactory beanFactory) {
        listableBeanFactory = (DefaultListableBeanFactory) beanFactory;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (tags == null) {
            tags = MapBuilder.of("default", "/**");
        }
        for (Map.Entry<String, String> entry : tags.entrySet()) {
            if (!listableBeanFactory.containsBean(entry.getKey())) {
                listableBeanFactory.registerSingleton(entry.getKey(), createDocket(entry.getKey(), entry.getValue()));
            }
        }
    }

    public Docket createDocket(String groupName, String prefix) throws Exception {
        ApiInfo apiInfo = new ApiInfoBuilder().build();
        String pom = System.getProperty("user.dir") + File.separator + "pom.xml";
        if (new File(pom).exists()) {
            Model model = new MavenXpp3Reader().read(new FileReader(pom));
            Contact contact = new Contact(model.getGroupId(), "", "1316851612@qq.com");
            apiInfo = new ApiInfoBuilder().title(model.getArtifactId()).description(model.getDescription())
                    .termsOfServiceUrl(model.getUrl()).version(model.getVersion()).contact(contact).build();
        }
        return new Docket(DocumentationType.OAS_30).groupName(groupName).enable(enabled).apiInfo(apiInfo).select()
                .apis(RequestHandlerSelectors.withClassAnnotation(ApiResource.class))
                .paths(PathSelectors.ant(prefix)).build();
    }

    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    assert field != null;
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }

//    @Bean
//    public OpenApiExtensionResolver markdownResolver(Knife4jProperties knife4jProperties, ClientInfo clientInfo) {
//        Knife4jHttpBasic knife4jHttpBasic = new Knife4jHttpBasic();
//        knife4jHttpBasic.setEnable(true);
//        knife4jHttpBasic.setUsername(clientInfo.getClientId());
//        knife4jHttpBasic.setPassword(clientInfo.getClientSecret());
//        knife4jProperties.setBasic(knife4jHttpBasic);
//        OpenApiExtendSetting setting = knife4jProperties.getSetting();
//        if (setting == null) {
//            setting = new OpenApiExtendSetting();
//        }
//        return new OpenApiExtensionResolver(setting, knife4jProperties.getDocuments());
//    }
}